package com.htime.exception;

import com.htime.domain.CommonRes;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by HTime on 2017/3/5.
 */
@ControllerAdvice
public class GlobalExceptionHandler {

//    @ExceptionHandler(value = RcException.class)
//    @ResponseBody
//    public CommonRes jsonSelfErrorHandler(HttpServletRequest req, RcException e) throws Exception {
//        CommonRes res = new CommonRes();
//        if(null == e.getRc())
//            res.setRc(CommonRes.RES_RUNTIME_EXCEPTION);
//        else
//            res.setRc(e.getRc());
//        res.setErrorInfo(e.getMessage());
//        res.setServerTime(new Date());
//        res.setRequestUrl(req.getRequestURL().toString());
//        return res;
//    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonRes jsonErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        CommonRes res = new CommonRes();
        if(e instanceof RcException) {
            RcException rcException = (RcException)e;
            if(null == rcException.getRc())
                res.setRc(CommonRes.RES_RUNTIME_EXCEPTION);
            else
                res.setRc(rcException.getRc());
        } else {
            res.setRc(CommonRes.RES_RUNTIME_EXCEPTION);
        }
        res.setErrorInfo(e.getMessage());
        res.setServerTime(new Date());
        res.setRequestUrl(req.getRequestURL().toString());
        return res;
    }

}
